from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from .models import Area
from rest_framework.response import Response
from .serializers import AreaSerializer, SubsSerializer
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin


# Create your views here.
# class AreaListView(APIView):
#     """查询所有省"""
#     def get(self, request):
#         qs = Area.objects.filter(parent=None)
#         serializer = AreaSerializer(qs, many=True)
#         return Response(serializer.data)
#
# class AreaDetailView(APIView):
#     """查询单一省或市"""
#     def get(self, request, pk):
#         try:
#             area = Area.objects.get(id=pk)
#         except Area.DostNotExist:
#             return Response({'message': '无效pk'}, status=status.HTTP_400_BAD_REQUEST)
#         serializer = SubsSerializer(area)
#         return Response(serializer.data)

class AreaViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    # 指定查询集
    def get_queryset(self):
        if self.action == 'list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()

    # 指定序列化器
    def get_serializer_class(self):
        if self.action == 'list':
            return AreaSerializer
        else:
            return SubsSerializer
